<?php

namespace App\Http\Services;


use App\Exceptions\ServiceException;
use App\Exceptions\ServiceExceptionConstant;
use App\Http\Repositories\Daos\User\UserDao;
use App\Http\Repositories\Redis\UserRedis;
use App\Http\Requests\UserContext;
use App\Models\Users;
use App\Util\Helper;
use Illuminate\Http\Request;


class UserCenterService extends BaseService
{
    protected $userDao;

    public function __construct(UserDao $userDao)
    {
        $this->userDao = $userDao;
    }

    public function userInfo(Request $request)
    {
        $userId = $request->userId;
        return UserRedis::getRedisInstance()->getNode($userId);
    }

    public function updateUserInfo(UserContext $userContext)
    {
        $userId = $userContext->getId();
        $post   = request()->input();
        $user   = Users::where('id', $userId)->first();
        if (!$user || empty($user)) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('用户不存在或未登录'));
        }
        if (empty($post['password']) || empty($post['new_password']) || empty($post['confirm_password'])) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('请填写密码'));
        }
        $mdPassword = Helper::password($post['password'], $user['salt']);
        if ($mdPassword != $user['password']) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('原密码错误'));
        }
        if ($post['new_password'] != $post['confirm_password']) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('新密码两次不一样'));
        }
        $newMdPassword = Helper::password($post['new_password'],$user['salt']);
        $user->password = $newMdPassword;
        $user->save();
        return true;
    }
}
